﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using static System.Collections.Specialized.BitVector32;

namespace Control_DB_Railway
{
    /// <summary>
    /// Логика взаимодействия для MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        Entities entities = new Entities();

        public MainWindow()
        {
            InitializeComponent();
            
            // Заполнение ListBox "Станция"
            foreach (var station in entities.Stations)
                listBox_Station.Items.Add(station);

            // Заполнение ListBox "Тип станции"
            foreach (var typeStation in entities.TypeStation)
                listBox_TypeStation.Items.Add(typeStation);

            // Заполнение ListBox "Дорога"
            foreach (var road in entities.Roads)
                listBox_Road.Items.Add(road);

            // Заполнение comboBox_StationLocation  "Станция"
            foreach (var location in entities.Stations)
                comboBox_StationLocation.Items.Add(location.location);

            // Заполнение comboBox_TypeRoad "Дорога"
            foreach (var typeRoad in entities.Roads)
                comboBox_TypeRoad.Items.Add(typeRoad.typeRoad);

            // Заполнение comboBox_CategoryQuality "Дорога"
            foreach (var categoryQuality in entities.Roads)
                comboBox_CategoryQuality.Items.Add(categoryQuality.categoryQuality);
        }

        /* Отображение информации в ListBox "Станция" */
        private void listBox_Station_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var selectStation = listBox_Station.SelectedItem as Stations;

            if (selectStation != null)
            {
                textBox_Station.Text = selectStation.nameStation;
                checkBox_overheadTransition.IsChecked = selectStation.overheadTransition;
                comboBox_StationLocation.SelectedItem = (from location in entities.Stations
                                                         where location.stationID ==
                                                         selectStation.stationID
                                                         select location).Single<Stations>();
            }
            else
            {
                textBox_Station.Text = "";
                checkBox_overheadTransition.IsChecked = false;
                comboBox_StationLocation.SelectedIndex = -1;
            }
        }

        // ИСПРАВЛЯТЬ! //
        /* Нажатие по кнопке "Добавить/изменить станцию" */
        private void button_AddRecord_Station_Click(object sender, RoutedEventArgs e)
        {
            var station = listBox_Station.SelectedItem as Stations;

            if (textBox_Station.Text == "" || comboBox_StationLocation.SelectedIndex == -1)
                MessageBox.Show("Заполните все поля!", "Ошибка!", MessageBoxButton.OK,
                                 MessageBoxImage.Error);

            else
            {
                if (station == null)
                {
                    station = new Stations();
                    entities.Stations.Add(station);         // добавляем запись в БД
                    listBox_Station.Items.Add(station);     // добавляем запись в ListBox
                }

                station.nameStation = textBox_Station.Text;
                station.overheadTransition = (bool)checkBox_overheadTransition.IsChecked;
                station.location = (comboBox_StationLocation.SelectedItem as Stations).location;
                entities.SaveChanges();
                listBox_Station.Items.Refresh();

                MessageBox.Show("Успешное сохранение/добавление записи!");
            }

            
        }

        /* Удаление записи "Станции" */
        private void button_DeleteRecord_Station_Click(object sender, RoutedEventArgs e)
        {
            var rezult = MessageBox.Show("Вы уверены, что хотите удалить запись?", "Удаление", 
                                          MessageBoxButton.YesNo, MessageBoxImage.Question);

            if (rezult == MessageBoxResult.No)
                return;

            var delete_station = listBox_Station.SelectedItem as Stations;

            if (delete_station != null)
            {
                entities.Stations.Remove(delete_station);
                entities.SaveChanges();
                textBox_Station.Clear();
                listBox_Station.Items.Remove(delete_station);
                checkBox_overheadTransition.IsEnabled = false;
                comboBox_StationLocation.SelectedIndex = -1;
            }
            else
                MessageBox.Show("Нет удаляемых объектов!", "Ошибка", MessageBoxButton.OK,
                                 MessageBoxImage.Warning);
        }

        /* Очистка полей "Станции" */
        private void button_ClearStation_Click(object sender, RoutedEventArgs e)
        {
            textBox_Station.Text = "";
            checkBox_overheadTransition.IsEnabled = false;
            comboBox_StationLocation.SelectedIndex = -1;
            listBox_Station.SelectedIndex = -1;
            textBox_Station.Focus();
        }

        /* Отображение информации в ListBox "Тип станции" */
        private void listBox_TypeStation_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var selectTypeStation = listBox_TypeStation.SelectedItem as TypeStation;

            if (selectTypeStation != null)
            {
                textBox_TypeStation.Text = selectTypeStation.nameTypeStation;
                checkBox_passagerService.IsChecked = selectTypeStation.passagerService;
            }
            else
            {
                textBox_TypeStation.Text = "";
                checkBox_passagerService.IsChecked = false;
            }
        }

        /* Добавление/сохранение записи в "Типе станции" */
        private void button_AddRecord_TypeStation_Click(object sender, RoutedEventArgs e)
        {
            var typeStation = listBox_TypeStation.SelectedItem as TypeStation;

            if (textBox_TypeStation.Text == "")
                MessageBox.Show("Напишите название!", "Ошибка!", MessageBoxButton.OK,
                                 MessageBoxImage.Error);

            else
            {
                if (typeStation == null)
                {
                    typeStation = new TypeStation();
                    entities.TypeStation.Add(typeStation);         // добавляем запись в БД
                    listBox_TypeStation.Items.Add(typeStation);    // добавляем запись в ListBox
                }

                typeStation.nameTypeStation = textBox_TypeStation.Text;
                typeStation.passagerService = (bool)checkBox_passagerService.IsChecked;
                entities.SaveChanges();
                listBox_TypeStation.Items.Refresh();

                MessageBox.Show("Успешное сохранение/добавление записи!");
            }
        }

        /* Удаление записи "Тип станции" */
        private void button_DeleteRecord_TypeStation_Click(object sender, RoutedEventArgs e)
        {
            var rezult = MessageBox.Show("Вы уверены, что хотите удалить запись?", "Удаление",
                                          MessageBoxButton.YesNo, MessageBoxImage.Question);

            if (rezult == MessageBoxResult.No)
                return;

            var delete_typeStation = listBox_TypeStation.SelectedItem as TypeStation;

            if (delete_typeStation != null)
            {
                entities.TypeStation.Remove(delete_typeStation);
                entities.SaveChanges();
                textBox_TypeStation.Clear();
                listBox_TypeStation.Items.Remove(delete_typeStation);
                checkBox_passagerService.IsEnabled = false;
            }
            else
                MessageBox.Show("Нет удаляемых объектов!", "Ошибка", MessageBoxButton.OK,
                                 MessageBoxImage.Warning);
        }

        /* Очистка полей "Станции" */
        private void button_ClearTypeStation_Click(object sender, RoutedEventArgs e)
        {
            textBox_TypeStation.Text = "";
            checkBox_passagerService.IsEnabled = false;
            listBox_TypeStation.SelectedIndex = -1;
            textBox_TypeStation.Focus();
        }

        /* Отображение данных в ListBox "Дороги" */
        private void listBox_Road_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var selectRoad = listBox_Road.SelectedItem as Roads;

            if (selectRoad != null)
            {
                textBox_NameRoad.Text = selectRoad.nameRoad;
                comboBox_TypeRoad.SelectedItem = (from typeRoad in entities.Roads
                                                         where typeRoad.roadID ==
                                                         selectRoad.roadID
                                                         select typeRoad).Single<Roads>();

                comboBox_CategoryQuality.SelectedItem = (from categoryQuality in entities.Roads
                                                         where categoryQuality.roadID ==
                                                         selectRoad.roadID
                                                         select categoryQuality).Single<Roads>();
            }
            else
            {
                textBox_TypeStation.Text = "";
                checkBox_passagerService.IsChecked = false;
            }
        }

        /* Добавление/сохранение записи в "Дорогу" */
        private void button_AddRecord_Road_Click(object sender, RoutedEventArgs e)
        {
            var Road = listBox_Road.SelectedItem as Roads;

            if (textBox_NameRoad.Text == "" || comboBox_TypeRoad.SelectedIndex == -1 ||
                comboBox_CategoryQuality.SelectedIndex == -1)
                MessageBox.Show("Заполните все поля!", "Ошибка!", MessageBoxButton.OK,
                                 MessageBoxImage.Error);
            else
            {
                if (Road == null)
                {
                    Road = new Roads();
                    entities.Roads.Add(Road);               // добавляем запись в БД
                    listBox_Road.Items.Add(Road);           // добавляем запись в ListBox
                }

                Road.nameRoad = textBox_NameRoad.Text;
                Road.typeRoad = (comboBox_TypeRoad.SelectedItem as Roads).typeRoad;
                Road.categoryQuality = (comboBox_CategoryQuality.SelectedItem as Roads).categoryQuality;

                entities.SaveChanges();
                listBox_TypeStation.Items.Refresh();

                MessageBox.Show("Успешное сохранение/добавление записи!");
            }
        }

        /* Удаление записи в "Дороге" */
        private void button_DeleteRecord_Road_Click(object sender, RoutedEventArgs e)
        {
            var rezult = MessageBox.Show("Вы уверены, что хотите удалить запись?", "Удаление",
                                          MessageBoxButton.YesNo, MessageBoxImage.Question);

            if (rezult == MessageBoxResult.No)
                return;

            var delete_road = listBox_Road.SelectedItem as Roads;

            if (delete_road != null)
            {
                entities.Roads.Remove(delete_road);
                entities.SaveChanges();
                textBox_Station.Clear();

                listBox_Road.Items.Remove(delete_road);
                comboBox_TypeRoad.SelectedIndex = -1;
                comboBox_CategoryQuality.SelectedIndex = -1;
            }
            else
                MessageBox.Show("Нет удаляемых объектов!", "Ошибка", MessageBoxButton.OK,
                                 MessageBoxImage.Warning);
        }

        /* Очистка полей "Дороги" */
        private void button_ClearRoad_Click(object sender, RoutedEventArgs e)
        {
            textBox_NameRoad.Text = "";
            comboBox_CategoryQuality.SelectedIndex = -1;
            comboBox_TypeRoad.SelectedIndex = -1;
            textBox_NameRoad.Focus();
        }
    }
}
